<script setup lang='ts'>
import {ref, reactive, PropType, onBeforeMount, watch} from 'vue'
import {FormRules, ElMessage} from 'element-plus'
import {FromItem} from '@/components/dFrom/dFrom'
import {ItemGroupFormInfor, saveItemGroupInfor, getDepartmentList, getCategoryList} from '@/api/physicalExaminationManager/projectPortfolio'
import {DialogType, SeleteData} from '@/api/config'
import dDialog from '@/components/dDialog/dDialog.vue'
import dFrom from '@/components/dFrom/dFrom.vue'
import {Normal, Alphanumeric, PositiveInteger, Price} from '@/util/common'
import useStore from '@/store/common'
import {transfDicArrData, getObjectByKey} from '@/util/common'
import useCommon from '@/store/common'
//是否显示
const props = defineProps({
  //显示
  showDialog:{
    type:Boolean,
    required:true
  },
  //弹窗类型
  dialogType:{
    type:String as PropType<DialogType>,
    required:true
  },
  //数据
  itemGroupFormData:{
    type:Object as PropType<ItemGroupFormInfor>,
    required:true
  }


})

const {store} = useStore.setup()

const emits = defineEmits(['close'])

//字典数据列表  检查类型 检验结果类型 单位 精度
const checkTypeList = ref<Array<SeleteData>>([])
const selectList:Array<SeleteData> = [{label:'是', value:true}, {label:'否', value:false}]

// 弹窗标题定义
const title = ref('')

// 弹窗标题设置
const initTitle = () => {
  if (props.dialogType === 'add') {
    title.value = '新增项目组合'
  }
  else if (props.dialogType === 'edit') {
    title.value = '编辑项目组合'
  }
}

//信息
const formData:ItemGroupFormInfor = reactive(props.itemGroupFormData)

// 显示加载状态
const showSaveLoading = ref(false)

// 表单规则
const rules = reactive<FormRules>({
  itemGroupCode:[
    {required:true, message: '请输入项目编码', trigger: ['change', 'blur']},
    {required:true, message:'长度应不超过50个字符', max:50, trigger: ['change', 'blur']},
    {required:true, message:'应输入字母、数字', pattern:Alphanumeric, trigger:['change', 'blur']}
  ],
  itemGroupName:[
    {required:true, message: '请输入项目名称', trigger: ['change', 'blur']},
    {required:true, message:'长度应不超过50个字符', max:50, trigger: ['change', 'blur']},
    {required:true, message:'应输入汉字、字母、数字、字符', pattern:Normal, trigger:['change', 'blur']}
  ],
  checkType:[
    {required:true, message: '请选择检查类型', trigger: ['change', 'blur']}
  ],
  deptId:[
    {required:true, message: '请选择所属科室', trigger: ['change', 'blur']}
  ],
  inspectCategoryId:[
    {required:true, message: '请选择体检大类', trigger: ['change', 'blur']}
  ],
  price:[
    {required:true, message:'请输入价格', trigger: ['change', 'blur']},
    {required:true, message:'长度应不超过10个字符', max:10, trigger: ['change', 'blur']},
    {required:true, message:'应输入不超过2位小数的数字', pattern:Price, trigger:['change', 'blur']}
  ],
  sort:[
    {required:true, message:'请输入排序', trigger: ['change', 'blur']},
    {required:true, message:'应输入正整数', pattern:PositiveInteger, trigger:['change', 'blur']}
  ]
})

//表单项
const fromItems = ref<Array<FromItem>>([
  {label:'项目组合编码', placeholder:'请输入项目组合编码', prop:'itemGroupCode', type:'input', disabled:formData.isFixed && formData.checkType === 1},
  {label:'项目组合名称', placeholder:'请输入项目组合名称', prop:'itemGroupName', type:'input', disabled:formData.isFixed && formData.checkType === 1},

  {label:'检查类型', placeholder:'请选择检查类型', prop:'checkType', type:'selete', seleteData:checkTypeList.value, disabled:props.dialogType === 'edit', notClearable:true},
  {label:'所属科室', placeholder:'请选择所属科室', prop:'deptId', type:'selete', seleteData:[], disabled:formData.isFixed && formData.checkType === 1 },
  {label:'体检大类', placeholder:'请选择体检大类', prop:'inspectCategoryId', type:'selete', seleteData:[], disabled:formData.isFixed && formData.checkType === 1},

  {label: '单价',  placeholder:'请输入单价', prop: 'price',  type: 'slot', slotName:'price'},

  {label:'必填项', placeholder:'是否必填项', prop:'isRequired', type:'selete', seleteData:selectList },
  {label:'是否在报告显示', placeholder:'是否在报告显示', prop:'isShow', type:'selete', seleteData:selectList },
  {label:'打印条码', placeholder:'是否打印条码', prop:'isPrintBarcode', type:'selete', seleteData:selectList },

  {label:'排序', placeholder:'请输入排序', prop:'sort', type:'input' }
])

// 更新体检大类选项
// const categoryData = ref<Array<SeleteData>>([])
const getCategoryData = (checkType?:number) => {
  const item = getObjectByKey(fromItems.value, 'prop', 'inspectCategoryId')
  if (item && item.type === 'selete') {
    item.seleteData = []

    getCategoryList({checkType}).then((res) => {
      const {data} = res.data
      let hasTag = false
      item.seleteData = data.map(category => {
        if (category.id === formData.inspectCategoryId) hasTag = true
        return {
          label:category.categoryName,
          value:category.id
        }
      })
      if (!hasTag) formData.inspectCategoryId = ''

    }).catch((error) => {
      console.warn(error)
      item.seleteData = []
      formData.inspectCategoryId = ''
    })
  }
}
// 更新科室选项
// const departmentData = ref<Array<SeleteData>>([])
const getDepartmentData = (checkType?:number) => {
  const item = getObjectByKey(fromItems.value, 'prop', 'deptId')
  if (item && item.type === 'selete') {
    item.seleteData = []
    getDepartmentList({checkType}).then(res => {
      const {data} = res.data
      let hasTag = false
      item.seleteData = data.map(item => {
        if (item.id === formData.deptId) hasTag = true
        return {
          label:item.deptName,
          value:item.id
        }
      })
      if (!hasTag) formData.deptId = ''
    }).catch((error) => {
      console.warn(error)
      item.seleteData = []
      formData.deptId = ''
    })
  }

}

watch(() => formData.checkType, (newValue) => {
  if (newValue) {
    getCategoryData(newValue)
    getDepartmentData(newValue)
  }
}, {
  immediate:true
})

// const fromItem = ref([...fromItems.value])

//表单清除控制
const resetFieldsFlag = ref(false)
const validateFlag = ref(false)

// 确认按钮
const onConfirm = () => {
  validateFlag.value = !validateFlag.value
}

//关闭
const onClose = () => {
  emits('close')
  //关闭后清除表单数据以及表单验证数据 可根据具体业务自行调整
  resetFieldsFlag.value = !resetFieldsFlag.value
}

//取消按钮
const onCancel = () => {
  onClose()
}

//表单验证通过事件
const onSubmit = () => {
  showSaveLoading.value = true
  saveItemGroupInfor(formData).then(() => {
    showSaveLoading.value = false
    ElMessage.success('保存成功！')
    useCommon.setup().store.getFields() // 获取开始体检-体检项目的必填字段
    emits('close')
  }).catch((error) => {
    showSaveLoading.value = false
    console.warn(error)
  })
}
//获取字典
const getDic = () => {
  store.getDicData('check_type').then((res) => {
    const list:Array<SeleteData> = transfDicArrData(res)
    list.forEach((item) => {
      checkTypeList.value.push(item)
    })
  })
}

onBeforeMount(() => {
  getDic()
  initTitle()
})

</script>

<template>
  <d-dialog
    :title="title"
    custom-class="edit"
    width="918px"
    :show-dialog="showDialog"
    :show-save-loading="showSaveLoading"
    button-align="d-comon-flex-justend"
    @cancel="onCancel"
    @confirm="onConfirm"
    @close="onClose"
  >
    <d-from
      label-position="right"
      :label-width="120"
      :reset-fields-flag="resetFieldsFlag"
      :validate-flag="validateFlag"
      :rules="rules"
      method="post"
      :form-data="formData"
      :form-items="fromItems"
      :form-line-num="2"
      @submit="onSubmit"
    >
      <template #price>
        <el-input v-model="formData.price" placeholder="请输入单价">
          <template #append>
            元
          </template>
        </el-input>
      </template>
    </d-from>
  </d-dialog>
</template>

<style scoped lang="less">
.el-input{
  :deep(.el-input-group__append) {
    background: #dcdee2 !important;
    width:40px;
    color: var(--d-font-color-text);
  }
}
</style>